<template>
  <div class="serial-terminal" v-if="isOpen">
    <div class="terminal-output" ref="outputRef">
      <div v-for="(line, idx) in lines" :key="idx">{{ line }}</div>
    </div>
    <div class="terminal-input">
      <input v-model="inputText" placeholder="输入发送内容" @keydown.enter="sendData" />
      <button @click="sendData">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUnmount, nextTick } from 'vue';
import serialService from '../services/serialService';



// 从父组件注入 isOpen 标记
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true
  }
});
const lines = ref([]);
const inputText = ref('');
const outputRef = ref(null);

// 1. 当 isOpen 变为 true 时，启动读循环
watch(() => props.isOpen, async (open) => {
  if (open) {
    lines.value = []; // 清空终端输出
    await serialService.startReading(onDataReceived);
  } else {
    await serialService.stopReading();
  }
});

// 当收到数据时，追加到 lines 数组并自动滚到底部
function onDataReceived(text) {
  lines.value.push(text);
  nextTick(() => {
    const el = outputRef.value;
    el.scrollTop = el.scrollHeight;
  });
}

// 2. 发送输入框内容到串口
async function sendData() {
  if (!inputText.value) return;
  try {
    await serialService.writeData(inputText.value + '\n');
    lines.value.push('▶ ' + inputText.value); // 回显
    inputText.value = '';
    nextTick(() => {
      const el = outputRef.value;
      el.scrollTop = el.scrollHeight;
    });
  } catch (err) {
    alert('发送失败：' + err.message);
  }
}

// 3. 组件卸载时确保关闭读循环
onBeforeUnmount(async () => {
  if (isOpen.value) {
    await serialService.stopReading();
  }
});
</script>

<style scoped>
.serial-terminal {
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  height: 300px;
}
.terminal-output {
  flex: 1;
  background: #1e1e1e;
  color: #f1f1f1;
  font-family: monospace;
  padding: 8px;
  overflow-y: auto;
}
.terminal-input {
  display: flex;
  border-top: 1px solid black;
}
.terminal-input input {
  flex: 1;
  padding: 8px;
  font-size: 14px;
}
.terminal-input input:focus {
  outline: none;
}
.terminal-input button {
  padding: 8px 12px;
  background: #409eff;
  border: none;
  color: white;
  cursor: pointer;
}
.terminal-input button:hover {
  background: #66b1ff;
}
</style>